<template>
  <div class="answer-show-container">
    <transition-group v-if="questions && questions.length" name="list-fade" tag="div" class="questions-container">
      <el-card
        v-for="(item, index) in questions"
        :key="item.id"
        class="question-card"
        :body-style="{ padding: '0' }"
        :class="{ 'answered': validatedStatus[item.id] }"
      >
        <div slot="header" class="card-header">
          <div class="header-main">
            <span class="q-index">Q{{ index + 1 }}</span>
            <h3 class="q-title">{{ item.title }}</h3>
          </div>
        </div>

        <div class="card-body">
          <div v-if="item.options && item.options.length > 0" class="options-list">
            <div
              v-for="(opt, idx) in item.options"
              :key="opt.id"
              class="option-item"
              :class="getOptionClass(item, opt)"
              :data-checked="validatedStatus[item.id]"
              @click="selectOption(item, opt)"
            >
              <div class="opt-content">
                <span class="opt-label">{{ getOptionLabel(idx) }}</span>
                <span class="opt-text">{{ opt.content }}</span>
              </div>

              <div class="opt-icon">
                <i
                  v-if="validatedStatus[item.id] && isRealCorrect(item, opt) && (isSelected(item, opt) || showCorrectMap[item.id])"
                  class="fas fa-check-circle correct-icon"
                />
                <i
                  v-if="validatedStatus[item.id] && isSelected(item, opt) && !isRealCorrect(item, opt)"
                  class="fas fa-times-circle wrong-icon"
                />
              </div>
            </div>
          </div>

          <div v-else class="no-options">
            <el-alert title="此题为非选择题，请核对后查看解析。" type="info" show-icon :closable="false"/>
          </div>
        </div>

        <div class="card-actions">
          <template v-if="!validatedStatus[item.id]">
            <el-button
              v-if="userAnswers[item.id] || !item.options"
              type="success"
              icon="fas fa-check-double"
              @click="checkOne(item)"
            >
              核对本题
            </el-button>
          </template>

          <template v-else>
            <el-button
              v-if="userAnswers[item.id] && !isRealCorrect(item, {id: userAnswers[item.id]})"
              type="danger"
              icon="fas fa-eye"
              @click="toggleCorrect(item)"
            >
              {{ showCorrectMap[item.id] ? '隐藏正确答案' : '显示正确答案' }}
            </el-button>

            <el-button
              type="success"
              icon="fas fa-file-alt"
              @click="toggleAnalysis(item)"
            >
              {{ showAnalysisMap[item.id] ? '收起解析' : '查看解析' }}
            </el-button>
          </template>
        </div>

        <el-collapse-transition>
          <div v-show="showAnalysisMap[item.id]" class="analysis-wrapper">
            <div class="analysis-section">
              <div class="analysis-title">
                <i class="fas fa-lightbulb"/> 答案解析
              </div>
              <div class="analysis-content" v-html="item.analysis"/>
            </div>

            <div class="attempt-history"
                 v-if="answerHistory[item.id] && answerHistory[item.id].length"
            >
              <h4 class="history-title">作答记录</h4>

              <div
                v-for="h in answerHistory[item.id]"
                :key="h.attempt"
                class="history-item"
                :class="{ correct: h.correct, wrong: !h.correct }"
              >
                <span class="h-attempt">第 {{ h.attempt }} 次：</span>
                <span class="h-answer">选项 {{ findOptionLabel(item, h.answerId) }}</span>
                <i v-if="h.correct" class="fas fa-check-circle"></i>
                <i v-if="!h.correct" class="fas fa-times-circle"></i>
              </div>
            </div>
          </div>
        </el-collapse-transition>
      </el-card>
    </transition-group>

    <el-empty v-if="!questions || !questions.length" description="暂无题目数据" class="empty-container"/>

    <div v-if="questions && questions.length" class="footer-actions-bar">
      <el-button
        type="success"
        icon="fas fa-check-double"
        :disabled="isAllValidated||unansweredCount>0"
        @click="checkAll"
      >
        {{ isAllValidated ? '核对完成' : '核对答案' }}
      </el-button>
      <el-button
        type="warning"
        icon="fa-solid fa-handcuffs"
        :disabled="isAllValidated||unansweredCount>0"
        @click="startNewAttempt"
      >
        封档（{{ attemptCount }} 次作答）
      </el-button>

    </div>
  </div>
</template>

<script>
export default {
  name: 'AnswerShowUpdated',
  props: {
    initialData: {
      type: Array,
      default: () => null
    }
  },
  data() {
    return {
      userAnswers: {},
      validatedStatus: {},
      showAnalysisMap: {},
      showCorrectMap: {},
      // 模拟数据 (保持不变)
      mockData: [
        {
          'id': 1,
          'title': 'Labubu looks like a ______.',
          'options': [
            { 'id': 1, 'content': 'cat' },
            { 'id': 2, 'content': 'rabbit' },
            { 'id': 3, 'content': 'dog' }
          ],
          'answer_ids': '2',
          'analysis': '根据文章“I look like a rabbit.”可知,她像兔子。故选 <b>B</b>。' // 稍微修改增加了一点 HTML 演示 v-html
        },
        {
          'id': 2,
          'title': 'Labubu has teeth eyes and ___',
          'options': [
            { 'id': 1, 'content': 'small; short' },
            { 'id': 2, 'content': 'big; short' },
            { 'id': 3, 'content': 'big; long' }
          ],
          'answer_ids': '3',
          'analysis': '细节理解题。题干意为：Labubu有___眼睛和___牙齿。根据文章"I have two long ears and big eyes."及"When （当.....·时候）I smile，you can see my long teeth too.”可知,她有大眼晴和长牙齿。故选 <b>C</b>。'
        }
      ],
      answerHistory: {},
      attemptCount: 1
    }
  },
  computed: {
    questions() {
      return this.initialData || this.mockData
    },
    isAllValidated() {
      if (!this.questions) return false
      return this.questions.every(q => this.validatedStatus[q.id])
    },
    unansweredCount() {
      return this.questions.filter(q => !this.userAnswers[q.id] && q.options).length
    }
  },
  mounted() {
    this.questions.forEach(q => {
      this.$set(this.answerHistory, q.id, [])
    })
  },
  methods: {
    startNewAttempt() {
      this.questions.forEach(question => {
        if (!this.validatedStatus[question.id]) {
          this.answerHistory[question.id].push({
            attempt: this.attemptCount,
            answerId: this.userAnswers[question.id],
            correct: this.isRealCorrect(question, { id: this.userAnswers[question.id] })
          })
        }
      })

      this.attemptCount++

      this.userAnswers = {}
      this.validatedStatus = {}
      this.showCorrectMap = {}
      this.showAnalysisMap = {}

      this.$notify({ type: 'success', message: `已开始第 ${this.attemptCount} 次作答` })
    },

    getOptionLabel(index) {
      return String.fromCharCode(65 + index)
    },
    selectOption(question, option) {
      if (this.validatedStatus[question.id]) return
      this.$set(this.userAnswers, question.id, option.id)
    },
    isSelected(question, option) {
      return this.userAnswers[question.id] === option.id
    },
    isRealCorrect(question, option) {
      return String(question.answer_ids) === String(option.id)
    },
    getOptionClass(question, option) {
      const isSelected = this.isSelected(question, option)
      const isValidated = this.validatedStatus[question.id]
      const isRealCorrect = this.isRealCorrect(question, option)

      if (!isValidated) {
        return { 'is-selected': isSelected }
      }

      const classes = {}
      if (isSelected) {
        isRealCorrect ? (classes['is-user-correct'] = true) : (classes['is-user-wrong'] = true)
      }

      if (this.showCorrectMap[question.id] && isRealCorrect) {
        classes['is-reveal-correct'] = true
      }
      return classes
    },
    checkOne(question) {
      if (!this.userAnswers[question.id] && question.options) {
        this.$notify({ type: 'warning', message: '请先选择一个选项' })
        return
      }
      this.$set(this.validatedStatus, question.id, true)
      // 自动展开解析体验更好
      this.$set(this.showAnalysisMap, question.id, true)

      this.answerHistory[question.id].push({
        attempt: this.attemptCount,
        answerId: this.userAnswers[question.id],
        correct: this.isRealCorrect(question, { id: this.userAnswers[question.id] })
      })
    },
    findOptionLabel(question, optId) {
      const idx = question.options.findIndex(o => o.id === optId)
      return String.fromCharCode(65 + idx)
    },
    toggleCorrect(question) {
      this.$set(this.showCorrectMap, question.id, !this.showCorrectMap[question.id])
    },
    toggleAnalysis(question) {
      this.$set(this.showAnalysisMap, question.id, !this.showAnalysisMap[question.id])
    },
    checkAll() {
      this.questions.forEach(q => {
        if (!this.validatedStatus[q.id]) {
          this.answerHistory[q.id].push({
            attempt: this.attemptCount,
            answerId: this.userAnswers[q.id],
            correct: this.isRealCorrect(q, { id: this.userAnswers[q.id] })
          })
        }

        this.$set(this.validatedStatus, q.id, true)
        this.$set(this.showAnalysisMap, q.id, true)
        this.toggleCorrect(q)
      })
      this.$notify({ type: 'success', message: '已核对所有答案' })
    }
  }
}
</script>

<style scoped>
/* 定义一些 CSS 变量方便统一管理颜色 */
:root {
  --primary-color: #409eff;
  --primary-light: #ecf5ff;
  --primary-gradient: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);

  --success-color: #67c23a;
  --success-bg: #f0f9eb;
  --success-border: #c2e7b0;

  --danger-color: #f56c6c;
  --danger-bg: #fef0f0;
  --danger-border: #fbc4c4;

  --text-main: #303133;
  --text-regular: #606266;
  --border-color-base: #dcdfe6;
  --bg-color-base: #f5f7fa;
}

/* 整体容器 - 增加柔和背景色 */
.answer-show-container {
  max-width: 800px; /* 限制最大宽度，大屏浏览更舒适 */
  min-width: 500px;
  background-color: #f6f8fa; /* 柔和的米灰色背景 */
  border-radius: 16px;
}

/* 题目容器 */
.questions-container {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 增加卡片间距 */
  margin-bottom: 10px;
}

/* 题目卡片 - 优化阴影和圆角 */
.question-card {
  border-radius: 16px !important;
  border: none !important; /* 移除默认边框，靠阴影塑造层次 */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.03) !important; /* 更精致的复合阴影 */
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  overflow: hidden;
}

.question-card:hover {
  transform: translateY(-4px); /* 悬浮感更强 */
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08), 0 4px 8px rgba(0, 0, 0, 0.04) !important;
}

/* 卡片头部 - 渐变背景 */
.card-header {
  padding: 18px 24px;
  background: linear-gradient(to right, #f0f8ff, #ffffff); /* 淡淡的蓝白渐变 */
  border-bottom: 1px solid #f0f0f0;
}

.header-main {
  display: flex;
  align-items: baseline; /* 基线对齐，使序号和标题更和谐 */
  gap: 15px;
}

.q-index {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px 12px;
  background-color: rgba(64, 158, 255, 0.15);
  color: var(--primary-color, #409eff);
  border-radius: 20px;
  font-weight: 700;
  font-size: 15px;
  flex-shrink: 0;
}

.q-title {
  margin: 0;
  font-size: 19px;
  color: var(--text-main, #303133);
  line-height: 1.5;
  font-weight: 600;
}

/* 卡片主体内容区 */
.card-body {
  padding: 24px 24px 10px;
}

/* 选项列表 */
.options-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

/* 选项项 - 核心交互区域 */
.option-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.25s ease;
  border: 2px solid transparent; /* 预留边框位置，避免抖动 */
  background-color: #eef4f3;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.02);
  position: relative;
}

/* 选项悬停态 */
.option-item:hover:not(.is-selected):not([data-checked="true"]) {
  background-color: #f2f8ff;
  border-color: #cce4ff;
  transform: translateY(-1px);
}

/* 选项内容布局 */
.opt-content {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

/* 选项标签 (A/B/C) */
.opt-label {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: #fff;
  color: #909399;
  border: 2px solid #e4e7ed;
  border-radius: 50%;
  font-weight: 700;
  font-size: 15px;
  flex-shrink: 0;
  transition: all 0.3s;
}

.opt-text {
  font-size: 17px;
  color: var(--text-regular, #606266);
  line-height: 1.4;
  font-weight: 500;
}

/* 状态图标 */
.opt-icon {
  margin-left: 15px;
  font-size: 22px;
  animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes popIn {
  from {
    opacity: 0;
    transform: scale(0.5);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.correct-icon {
  color: var(--success-color, #67c23a);
}

.wrong-icon {
  color: var(--danger-color, #f56c6c);
}

/* Let's enhance option states */

/* 选中状态 (未核对) */
.option-item.is-selected {
  background-color: var(--primary-light, #ecf5ff);
  border-color: var(--primary-color, #409eff);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.option-item.is-selected .opt-label {
  background-color: var(--primary-color, #409eff);
  border-color: var(--primary-color, #409eff);
  color: #fff;
}

/* 用户选对 */
.option-item.is-user-correct {
  background-color: var(--success-bg, #f0f9eb);
  border-color: var(--success-border, #c2e7b0);
}

.option-item.is-user-correct .opt-label {
  background-color: var(--success-color, #67c23a);
  border-color: var(--success-border, #c2e7b0);
  color: #fff;
}

.option-item.is-user-correct .opt-text {
  color: var(--success-color, #67c23a);
}

/* 用户选错 */
.option-item.is-user-wrong {
  background-color: var(--danger-bg, #fef0f0);
  border-color: var(--danger-border, #fbc4c4);
}

.option-item.is-user-wrong .opt-label {
  background-color: var(--danger-color, #f56c6c);
  border-color: var(--danger-border, #fbc4c4);
  color: #fff;
}

.option-item.is-user-wrong .opt-text {
  color: var(--danger-color, #f56c6c);
}

/* 显示正确答案 (当用户选错时的高亮) */
.option-item.is-reveal-correct {
  background-color: var(--success-bg, #f0f9eb);
  border: 2px dashed var(--success-color, #67c23a); /* 使用虚线区分 */
}

.option-item.is-reveal-correct .opt-label {
  color: var(--success-color, #67c23a);
  border-color: var(--success-color, #67c23a);
  background: #fff;
}

/* 卡片操作栏 */
.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 15px 24px;
  background-color: #fcfdfd;
  border-top: 1px solid #f5f7fa;
}

/* 解析区域 */
.analysis-wrapper {
  padding: 5px 24px 24px;
}

.analysis-section {
  background-color: #f8faff; /* 极淡的蓝色背景 */
  border-radius: 10px;
  padding: 20px;
  border-left: 4px solid var(--primary-color, #409eff);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03) inset;
}

.analysis-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 17px;
  color: var(--text-main, #303133);
  margin-bottom: 12px;
  font-weight: 600;
}

.analysis-title i {
  color: #e6a23c; /* 灯泡图标黄色 */
}

.analysis-content {
  font-size: 16px;
  color: #5a5e66;
  line-height: 1.7;
  text-align: justify;
}

/* 解析内容中的加粗样式 */
.analysis-content ::v-deep b {
  color: var(--primary-color, #409eff);
  font-weight: 700;
  background: rgba(64, 158, 255, 0.1);
  padding: 0 4px;
  border-radius: 4px;
}

/* 底部全局操作栏 */
.footer-actions-bar {
  position: sticky;
  bottom: 0;
  z-index: 10;
  display: flex;
  gap: 10px;
  justify-content: center;
  padding: 10px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
}

.footer-actions-bar .el-button {
  border-radius: 8px;
  padding: 8px 16px;
}

.footer-actions-bar .el-button i {
  margin-right: 6px;
}

.card-actions .el-button {
  border-radius: 8px;
  padding: 8px 16px;
}

.card-actions .el-button i {
  margin-right: 6px;
}

.attempt-history {
  margin-top: 18px;
  background: #fafafa;
  padding: 14px 18px;
  border-radius: 10px;
  border-left: 4px solid #409eff;
}

.history-title {
  font-weight: 700;
  margin-bottom: 10px;
  font-size: 15px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 0;
}

.history-item.correct {
  color: #67c23a;
}

.history-item.wrong {
  color: #f56c6c;
}

.h-attempt {
  font-weight: 600;
}

</style>
